package com.bci.pwtz.service.sms.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.log4j.Logger;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.exception.PwtzException;
import com.bci.pwtz.service.sms.SendSmsService;

public class SendSmsServiceImpl implements SendSmsService
{
    private final static Logger _logger        = Logger.getLogger(SendSmsServiceImpl.class);
    private static final String ENCODE_CHARSET = "GBK";

    @Override
    public String batchSend(String[] mobiles, String content, String cell, String sendTime) throws PwtzException, IOException
    {
        if (cell == null)
            cell = "";
        if (sendTime == null)
            sendTime = "";

        if (mobiles == null || mobiles.length == 0)
        {
            throw new PwtzException("短信接口中，接受短信号码数组不能为null且长度不能为0");
        }

        if (StringUtils.isBlank(content.trim()))
        {
            throw new PwtzException("短信接口中，短信内容不能为空");
        }
//        return "0";
        
        StringBuilder sb = new StringBuilder();
        String mobile = null;
        for (int i = 0; i < mobiles.length; i++)
        {
            mobile = mobiles[i];
            if (StringUtils.isBlank(mobile))
            {
                continue;
            }
            sb.append(",").append(mobiles[i]);
        }
        String mobileStr = sb.toString();
        if (mobileStr.length() > 0)
            mobileStr = mobileStr.substring(1);

        String encCorpID = URLEncoder.encode(PwtzConstants.SMS_INTERFACE_CORP_ID, ENCODE_CHARSET);
        String encPwd = URLEncoder.encode(PwtzConstants.SMS_INTERFACE_PASSWORD, ENCODE_CHARSET);
        String encMobiles = URLEncoder.encode(mobileStr, ENCODE_CHARSET);
        String encContent = URLEncoder.encode(content, ENCODE_CHARSET);
        String encCell = URLEncoder.encode(cell, ENCODE_CHARSET);
        String encSendTime = URLEncoder.encode(sendTime, ENCODE_CHARSET);

        sb = new StringBuilder();
        sb.append(PwtzConstants.SMS_INTERFACE_SEND_URL).append("?").append("CorpID=").append(encCorpID).append("&Pwd=").append(encPwd).append("&Mobile=").append(encMobiles).append("&Content=").append(encContent).append("&Cell=").append(encCell).append("&SendTime=").append(encSendTime);
        String url = sb.toString();
        if (_logger.isDebugEnabled())
        {
            _logger.debug("batchSend.smsSendUrl=" + url);
        }
        HttpGet get = new HttpGet(url);
        HttpClient client = new DefaultHttpClient();
        get.addHeader("Content-Type", "text/html; charset=GBK");
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, PwtzConstants.SMS_INTERFACE_TIMEOUT * 1000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, PwtzConstants.SMS_INTERFACE_TIMEOUT * 1000);
        HttpResponse response = null;
        try
        {
            response = client.execute(get);
        }
        catch (ClientProtocolException e)
        {
            _logger.error("调用短信下发接口客户端协议异常", e);
        }
        catch (IOException e)
        {
            _logger.error("调用短信下发接口IO异常", e);
        }
        // int status = response.getStatusLine().getStatusCode();

        BufferedReader rd = null;
        try
        {
            rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), ENCODE_CHARSET));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null)
            {
                result.append(line);
            }
            return result.toString();
        }
        catch (IllegalStateException e)
        {
            _logger.error("获取短信下发接口返回值时状态异常", e);
            throw e;
        }
        catch (IOException e)
        {
            _logger.error("获取短信下发接口返回值时IO异常", e);
            throw e;
        }
        finally
        {
            rd.close();
        }

        // System.out.println(result.toString());
        // if (status == 200)
        // {
        // System.out.println("Notification sent successfully.");
        // }
        // else
        // {
        // System.out.println("Failed to send the notification!");
        // }
    }

}
